package cn.cmcc.online.smsapi.sdk.util;

import java.util.Map;

import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;

/* SDK-428 huangzhiqiang 20160603 start */
public class BaseRunnable implements Runnable {
    /* IMOO-13 likuangkuang 20161017 start */
    protected long mLastExecuteTime = 0;
    protected long mExecuteInterval = Constant.MINUTE;
    /* IMOO-13 likuangkuang 20161017 end */
    
    private Map<String, Object> mExtendParams = null;
    private boolean mIsRunning = false;
    
    public Map<String, Object> getExtendParams() {
        return mExtendParams;
    }

    public void setExtendParams(Map<String, Object> extendParams) {
        mExtendParams = extendParams;
    }

    public final boolean isRunning() {
        return mIsRunning;
    }

    public void setThreadPriority() {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_LOWEST);
    }

    public void setInterval(long interval) {
    	mExecuteInterval = interval;
    }
    /**
     * 是否有联网权限
     * 
     * @return true:有权限 false:没有权限
     */
    public boolean checkAccessNetWork() {
        return NetUtil.checkAccessNetWork(2);
    }

    public void execute() {
    }

    protected boolean inQueryInterval() {
    	return (mLastExecuteTime + mExecuteInterval) > System.currentTimeMillis();
    }

    public boolean isInvalidExecute() {
        if (inQueryInterval()) {
            return true;
        }
        
        synchronized (this) {
            if (inQueryInterval()) {
                return true;
            }
            
            if (!checkAccessNetWork()) {
                return true;
            }
            
            mLastExecuteTime = System.currentTimeMillis();
            return false;
        }
    }

    @Override
    public final void run() {
        if (mIsRunning) {
            return;
        }
        
        synchronized (this) {
            if (mIsRunning) {
                return;
            }
            mIsRunning = true;
        }
        
        try {
            setThreadPriority();

            if (isInvalidExecute()) {
                return;
            }
            
            execute();
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "BaseRunnable run error:", e);
        } finally {
            mIsRunning = false;
        }
    }
}
/* SDK-428 huangzhiqiang 20160603 end */